import { getSignature } from './core/signature.js'
import { getLiveInfo } from './core/request'
import { DyCast } from './core/dycast'
import type { DyLiveInfo } from './core/dycast'


 
 
 
// 暴露函数到window对象供puppeteer调用
declare global {
  interface Window {
    connectLiveRoom: (roomId: string) => Promise<any>
    getLiveInfo: (roomId: string) => Promise<DyLiveInfo>
    // Puppeteer通信函数
    __puppeteerReceive?: (data: any) => void
    __puppeteerLog?: (level: string, ...args: any[]) => void
  }
}

// 向puppeteer发送数据的辅助函数
const sendToPuppeteer = (data: any) => {
  if (typeof window.__puppeteerReceive === 'function') {
    window.__puppeteerReceive(data)
  }else{
    console.log(  data);
  }
}

// 向puppeteer发送日志的辅助函数
const logToPuppeteer = (level: string, ...args: any[]) => {
  if (typeof window.__puppeteerLog === 'function') {
    window.__puppeteerLog(level, ...args)
  }
}

// 增强的连接直播间方法
const enhancedConnectLiveRoom = async (roomId: string) => {
  console.log(`🔗 开始连接直播间 ${roomId}...`)
  logToPuppeteer('info', `开始连接直播间 ${roomId}`)
  
  const dycast = new DyCast(roomId)
  
  // 监听连接打开事件
  dycast.on('open', (ev, info) => {
    console.log(`✅ 直播间 ${roomId} 连接成功!`)
    console.log(`📺 直播间 ${roomId} 信息:`, info)
    logToPuppeteer('info', `直播间 ${roomId} 连接成功`, info)
    
    // 向puppeteer发送连接成功事件
    sendToPuppeteer({
      type: 'connection_opened',
      roomId,
      info,
      timestamp: new Date().toISOString()
    })
  })
  
  // 监听弹幕消息
  dycast.on('message', (messages) => {
    // 打印扩展的用户信息
    messages.forEach(msg => {
      if (msg.user && msg.method === 'WebcastChatMessage') {
        console.log(`\n📋 [${roomId}] 用户信息详情:`, {
          基础信息: {
            id: msg.user.id,
            name: msg.user.name,
            gender: msg.user.gender,
            avatar: msg.user.avatar
          },
          扩展信息: {
            shortId: msg.user.shortId,
            signature: msg.user.signature,
            level: msg.user.level,
            city: msg.user.city,
            verified: msg.user.verified,
            userRole: msg.user.userRole,
            experience: msg.user.experience
          },
          等级认证: {
            payGrade: msg.user.payGrade,
            fansClub: msg.user.fansClub,
            anchorLevel: msg.user.anchorLevel,
            totalRechargeDiamondCount: msg.user.totalRechargeDiamondCount
          },
          商业权限: {
            withCommercePermission: msg.user.withCommercePermission,
            withFusionShopEntry: msg.user.withFusionShopEntry
          }
        })
        console.log('─'.repeat(50))
      }
    })
    
    // 向puppeteer发送弹幕消息
    sendToPuppeteer({
      type: 'messages',
      roomId,
      messages,
      timestamp: new Date().toISOString()
    })
  })
  
  // 监听连接关闭事件
  dycast.on('close', (code, reason) => {
    console.log(`❌ 房间 ${roomId} 连接关闭: ${code} - ${reason}`)
    logToPuppeteer('warn', `房间 ${roomId} 连接关闭`, { code, reason })
    
    // 向puppeteer发送连接关闭事件
    sendToPuppeteer({
      type: 'connection_closed',
      roomId,
      code,
      reason,
      timestamp: new Date().toISOString()
    })
  })
  
  // 监听错误事件
  dycast.on('error', (error) => {
    console.error(`🚨 房间 ${roomId} 连接错误:`, error)
    logToPuppeteer('error', `房间 ${roomId} 连接错误`, error)
    
    // 向puppeteer发送错误事件
    sendToPuppeteer({
      type: 'connection_error',
      roomId,
      error: error.message || error.toString(),
      timestamp: new Date().toISOString()
    })
  })
  
  // 监听重连事件
  dycast.on('reconnecting', (count) => {
    console.log(`🔄 房间 ${roomId} 正在重连... (第${count}次)`)
    logToPuppeteer('info', `房间 ${roomId} 正在重连`, { count })
    
    // 向puppeteer发送重连事件
    sendToPuppeteer({
      type: 'reconnecting',
      roomId,
      count,
      timestamp: new Date().toISOString()
    })
  })
  
  try {
    await dycast.connect()
    return {
      success: true,
      dycast,
      roomId,
      connectedAt: new Date().toISOString()
    }
  } catch (error) {
    console.error(`房间 ${roomId} 连接失败:`, error)
    
    // 向puppeteer发送连接失败事件
    sendToPuppeteer({
      type: 'connection_failed',
      roomId,
      error: error instanceof Error ? error.message : error?.toString(),
      timestamp: new Date().toISOString()
    })
    
    throw error
  }
}

// 增强的获取直播间信息方法
const enhancedGetLiveInfo = async (roomId: string) => {
  try {
    console.log(`📺 获取直播间 ${roomId} 信息...`)
    logToPuppeteer('info', `获取直播间 ${roomId} 信息`)
    
    const liveInfo = await getLiveInfo(roomId)
    console.log(liveInfo,"liveInfo");

    // 向puppeteer发送获取信息成功事件
    sendToPuppeteer({
      type: 'live_info_success',
      roomId,
      liveInfo,
      timestamp: new Date().toISOString()
    })
    
    return liveInfo
  } catch (error) {
    console.error(`获取直播间 ${roomId} 信息失败:`, error)
    logToPuppeteer('error', `获取直播间 ${roomId} 信息失败`, error)
    
    // 向puppeteer发送获取信息失败事件
    sendToPuppeteer({
      type: 'live_info_failed',
      roomId,
      error: error instanceof Error ? error.message : error?.toString(),
      timestamp: new Date().toISOString()
    })
    
    throw error
  }
}

// 暴露增强的方法
window.connectLiveRoom = enhancedConnectLiveRoom
window.getLiveInfo = enhancedGetLiveInfo

console.log('✅ 所有函数已暴露到 window 对象，支持 Puppeteer exposeFunction 通信')

 
